#include "stdafx.h"

#include "Dwarf.h"
#include "DwarfCraftsman.h"
#include "DwarfFarmer.h"
#include "DwarfMiner.h"
#include "DwarfWarriror.h"

#include "Parser.h"
#include "World.h"

unsigned int GetDwarfIndex()
{
	std::cout << "Select dwarfs"		<< std::endl;
	
	std::cout << "1. Dwarf farmer"		<< std::endl;
	std::cout << "2. Dwarf miner"		<< std::endl;
	std::cout << "3. Dwarf craftsman"	<< std::endl;
	std::cout << "4. Dwarf warriror"	<< std::endl;

	while (true)
	{
		char index = getchar();
		index -= 48;
		
		if (index > 0 && index < 9)
		{
			if (index > 0 && index < 5)
			{
				return index;
			}
		}
		
		if (index != -38)
			std::cout << "You enter incorrect data. Retry." << std::endl;
	}
}

std::shared_ptr<CDwarf> GetSelectedDwarf()
{
	switch (GetDwarfIndex())
	{
	case 1 :
		return std::shared_ptr<CDwarf>(new CDwarfFarmer());
	case 2 :
		return std::shared_ptr<CDwarf>(new CDwarfMiner());
	case 3 :
		return std::shared_ptr<CDwarf>(new CDwarfCraftsman());
	case 4 :
		return std::shared_ptr<CDwarf>(new CDwarfWarriror());
	}
}

void WorkWithConsole(CWorld & world, CParser & parser)
{
	std::cout << "Enter your expressions" << std::endl;
	std::cout << "right | left| forward | backward | say| go | stop | attack | work" << std::endl;
	std::cout << "while '('<variable>')' <expresion>" << std::endl;

	while (!std::cin.eof())
	{
		std::string expression;
		getline(std::cin, expression);
		std::vector<std::string> commands;
		if (parser.CheckExpression(expression, commands))
		{
			world.ExecuteCommands(commands);
		}
		else 
		{
			std::cout << "You enter incorrect command. Retry" << std::endl;
		}
	}
}

void WorkWithFile(CWorld & world, CParser & parser, std::string const & fileName)
{
	std::ifstream file(fileName);
	while (!file.eof())
	{
		std::string expression;
		getline(file, expression);
		std::vector<std::string> commands;
		if (parser.CheckExpression(expression, commands))
		{
			world.ExecuteCommands(commands);
		}
		else 
		{
			std::cout << "You enter incorrect command. Retry" << std::endl;
		}
	}
}

int main(int argc, char * argv[])
{
	CWorld world;
	world.AddDwarf(GetSelectedDwarf());

	CParser parser;

	std::cout << "Select, work with console or with file" << std::endl;
	std::cout << "1. Console" << std::endl;
	std::cout << "2. File" << std::endl;
	int index;
	std::cin >> index;
	if (index == 1)
	{
		WorkWithConsole(world, parser);
	}
	else
	{
		std::string fileName;
		std::cout << "Enter file name" << std::endl;
		std::cin >> fileName;
		WorkWithFile(world, parser, fileName.c_str());
	}

	return 0;
}

